/**
 * Created by user on 3/23/19.
 */
import React from 'react'

class ServerBgImage extends React.Component {
  constructor(p) {
    super(p)
    this.state = {
      loading: false,
      error: false,
      bg: p.bg
    }
  }
  componentWillReceiveProps(nextProps, props) {
    if (nextProps.bg != props.bg) {
      this.setState({bg: nextProps.bg})
    }
  }
  componentDidMount() {
    this.setState({ loading: true })
  }
  imageLoad = () => {
    this.setState({ loading: false })
    // console.log('imageLoad')
  }
  imageError = () => {
    // console.log('imageError')
    this.setState({ error: true, loading: false })
  }
  clickImage = () => {
    if (this.state.loading) {
      return
    }
    if (this.state.error) {
      this.setState({
        bg: `${this.props.bg}?v=${Date.now()}`,
        error: false,
        loading: true
      })
      return
    }
    this.props.onClick && this.props.onClick()
  }
  render() {
    let loadingImage = require('@images/default_image_loading.png')
    let errorImage = require('@images/default_error_image.jpg')
    let url = this.state.bg
    if (this.state.loading) {
      url = loadingImage
    }
    if (this.state.error) {
      url = errorImage
    }
    let className = `${this.props.className} ${this.state.loading || this.state.error ? 'loading' : ''}`
    return (
      <div onClick={this.clickImage} className={className} style={{backgroundImage: `url(${url})`}}>
        <img onError={this.imageError} onLoad={this.imageLoad} style={{with: 0, height: 0}} src={this.state.bg} alt=""/>
        {this.props.children ? this.props.children : null}
      </div>
    )
  }
}

export default ServerBgImage
